//
//  LoginViewController.m
//  birthdayCalculate
//
//  Created by 宋浩文的pro on 15/12/18.
//  Copyright © 2015年 宋浩文的pro. All rights reserved.
//

#import "LoginViewController.h"
#import <BmobSDK/Bmob.h>
#import "CommonTool.h"
#import "MBProgressHUD.h"
#import "UIView+Extension.h"
#import "MainTabBarController.h"

#define GetVerfiCodeUrl @"http://bazi.up1024.com/index.php?c=sms&a=send"

@interface LoginViewController ()<UITextFieldDelegate>

/** 手机号输入框 */
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTF;

/** 手机验证码 */
@property (weak, nonatomic) IBOutlet UITextField *codeTxetField;

/** 登录按钮 */
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

/** 登录用的遮罩 */
@property (nonatomic, strong) MBProgressHUD *loginHUD;


@end

@implementation LoginViewController


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.phoneNumberTF becomeFirstResponder];
}

/**
 *  判断是否登录
 *
 *  @return YES为已登录，NO为没有登录
 */
+ (BOOL)isLogin
{
    BmobUser *user = [BmobUser getCurrentUser];
    if (user) {
        return YES;
    } else {
        return NO;
    }
   
}

/**
 *  跳转到登录页面
 *
 *  @param viewController 来源控制器
 */
+ (void)presentToLoginVCWithController:(UIViewController *)viewController
{
    LoginViewController *loginVC = [[self alloc] init];
    
    [viewController presentViewController:loginVC animated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setChildView];
}



- (void)textFieldTextDidChanged:(UITextField *)textField
{
    if (self.phoneNumberTF.text.length != 0 && self.codeTxetField.text.length != 0) {
        self.loginBtn.enabled = YES;
    } else {
        self.loginBtn.enabled = NO;
    }
}

- (void)setChildView
{
    
    self.phoneNumberTF.layer.cornerRadius = 2;
    self.phoneNumberTF.layer.borderWidth = 1;
    self.phoneNumberTF.layer.borderColor = RGBCOLOR(222, 222, 222, 1).CGColor;
    self.phoneNumberTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 7, self.phoneNumberTF.height)];
    self.phoneNumberTF.leftViewMode = UITextFieldViewModeAlways;
    [self.phoneNumberTF addTarget:self action:@selector(textFieldTextDidChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.codeTxetField.layer.cornerRadius = 2;
    self.codeTxetField.layer.borderWidth = 1;
    self.codeTxetField.layer.borderColor = RGBCOLOR(222, 222, 222, 1).CGColor;
    self.codeTxetField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 7, self.phoneNumberTF.height)];
    self.codeTxetField.leftViewMode = UITextFieldViewModeAlways;
    [self.codeTxetField addTarget:self action:@selector(textFieldTextDidChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.loginBtn.layer.cornerRadius = 2;
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"login_highlight"] forState:UIControlStateHighlighted];
    [self.loginBtn setBackgroundImage:[UIImage imageNamed:@"login_disable"] forState:UIControlStateDisabled];
}


- (IBAction)back:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];

}

#pragma amrk --- 获取验证码
- (IBAction)getVerifycode:(id)sender
{
    if (self.phoneNumberTF.text.length != 11) {
        [CommonTool showHUDWillDismissText:@"请输入正确手机号" withTime:1];
    } else {
        [BmobSMS requestSMSCodeInBackgroundWithPhoneNumber:self.phoneNumberTF.text andTemplate:@"register" resultBlock:^(int number, NSError *error) {
            if (error) {
                NSLog(@"%@",error);
            } else {
            }
        }];
        
        [self verifyCountDown];
    }
}



// 验证码倒计时
- (void)verifyCountDown
{
    
    self.sendCaptchaBtn.hidden = YES;
    self.sendCaptchaBtn.userInteractionEnabled = NO;
    UIButton *btn = [[UIButton alloc]init];
    btn.userInteractionEnabled = NO;
    btn.backgroundColor = RGBCOLOR(222, 222, 222, 1);
    btn.frame = self.sendCaptchaBtn.frame;
    btn.layer.cornerRadius = 5;
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn];
    [self setTimeOut:btn];
}




#pragma amrk --- 登录按钮点击
- (IBAction)loginBtnClicked:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    self.loginHUD = [MBProgressHUD showHUDAddedTo:Window animated:YES];
    self.loginHUD.labelText = @"登录中...";
    
    [BmobUser signOrLoginInbackgroundWithMobilePhoneNumber:_phoneNumberTF.text andSMSCode:_codeTxetField.text block:^(BmobUser *user, NSError *error) {
        if (user) {
    
            [self.loginHUD hide:YES];
            [UIApplication sharedApplication].keyWindow.rootViewController = [[MainTabBarController alloc] init];
            
        } else {
    
            [self.loginHUD hide:YES];
            [CommonTool showError:@"验证码错误"];
        }
    }];

    
    
}






#pragma amrk --- 验证码倒计时
- (void)setTimeOut:(UIButton *)btn
{
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.sendCaptchaBtn.hidden = NO;
                btn.userInteractionEnabled = YES;
                self.sendCaptchaBtn.userInteractionEnabled = YES;
                [btn removeFromSuperview];
                //设置界面的按钮显示 根据自己需求设置
                                [self.sendCaptchaBtn setAttributedTitle:nil forState:UIControlStateNormal];
                                [self.sendCaptchaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                                [self.sendCaptchaBtn setTitleColor:RGBCOLOR(181, 118, 54, 1) forState:UIControlStateNormal];
                                self.sendCaptchaBtn.backgroundColor = [UIColor whiteColor];
            });
        }else{
            
            
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_disable_normal"] forState:UIControlStateNormal];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSString *strTime = [NSString stringWithFormat:@"已发送 %d", timeout];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:strTime];
                [str addAttribute:NSForegroundColorAttributeName value:RGBCOLOR(175, 176, 177, 1) range:NSMakeRange(0,4)];
                [str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(4,str.length - 4)];
                [btn setAttributedTitle:str forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}










- (void)bmobLogin
{
    [BmobUser logout];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:Window animated:YES];
    hud.labelText = @"登录中...";
    
    [BmobUser signOrLoginInbackgroundWithMobilePhoneNumber:self.phoneNumberTF.text andSMSCode:self.codeTxetField.text block:^(BmobUser *user, NSError *error) {
    
       
    }];

}

@end
